package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.IndustryDetialsBean;
import com.wnhz.work.yz.bean.LookDetailsBean;
import com.wnhz.work.yz.utils.GlideImageLoader;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.NoScrollGridView;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class IndustryDetialsActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView evaluation_recycler;
    private RecyclerView recycler_pack;
    private TextView package_des;
    private Banner banner;
    private List<IndustryDetialsBean.InfoEntity.CommentListEntity> comm = new ArrayList<>();
    private ImageView is_video;
    private RelativeLayout rl_is_video;
    private RecyclerView service_recycler;
    private IndustryDetialsBean.InfoEntity info = new IndustryDetialsBean.InfoEntity();
    private void initView() {
        banner = (Banner) findViewById(R.id.banner);
        package_des = (TextView) findViewById(R.id.package_des);
        recycler_pack = (RecyclerView) findViewById(R.id.recycler_pack);
        recycler_pack.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        is_video = (ImageView) findViewById(R.id.is_video);
        evaluation_recycler = (RecyclerView) findViewById(R.id.evaluation_recycler);
        evaluation_recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rl_is_video = (RelativeLayout) findViewById(R.id.rl_is_video);
        service_recycler = (RecyclerView) findViewById(R.id.service_recycler);
        service_recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        qqShare();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_industry_detials);
        initTilte();
        EventBus.getDefault().register(this);
        // MyApplication.getInstance().addDestoryActivity(this, "industry2");
        initView();
        initData();
    }

    private String goodsId;

    private void initData() {
        goodsId = getIntent().getStringExtra("goodsId");
        showDialog();
        //  upLoad();
    }

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("goods_id", goodsId);
        MyApplication.getInstance().jiji = goodsId;
        XUtil.Post(Url.BATH_MODELDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("==工业化内装套餐详情==", result + "");
                Gson gson = new Gson();
                IndustryDetialsBean bean = gson.fromJson(result, IndustryDetialsBean.class);
                info = bean.getInfo();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
                setData();
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    protected void onResume() {
        upLoad();
        super.onResume();
    }

    private void setData() {

        if ("1".equals(info.getIs_video())) {
            rl_is_video.setVisibility(View.VISIBLE);

            ImageLoader.getInstance().displayImage(info.getVideo_img(), is_video);
            is_video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(IndustryDetialsActivity.this, PlayVideoActivity.class);
                    intent.putExtra("img", info.getVideo_img());
                    intent.putExtra("videoUrl", info.getVideo_url());
                    intent.putExtra("title", "视频");
                    intent.putExtra("des", "来自优住分享的视频");
                    startActivity(intent);
                }
            });
        }
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(info.getPackage_slide());
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        //
        package_des.setText(info.getPackage_des());
        //套餐个数
        recycler_pack.setAdapter(new BaseRVAdapter(this, info.getPackage_list()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_recycler_pack;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                DecimalFormat df = new DecimalFormat("######0.00");
                if (info.getPackage_list().get(position).getPrice().equals("")){
                    holder.setTextView(R.id.price, "0.00");
                }else {
                    double price = Double.parseDouble(info.getPackage_list().get(position).getPrice());
                    Log.e("套餐价格",""+df.format(price));
                    if (df.format(price).equals("0.00")) {
                        holder.setTextView(R.id.price, info.getPackage_list().get(position).getTotal_price() + "");
                    } else {
                        holder.setTextView(R.id.price, info.getPackage_list().get(position).getPrice() + "");
                    }
                }
                holder.setTextView(R.id.name, info.getPackage_list().get(position).getName() + "");
                holder.setTextView(R.id.desc, info.getPackage_list().get(position).getDesc() + "");
                holder.getView(R.id.look_detials).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            MyApplication.getInstance().getUserBean().getToken();
                        } catch (Exception e) {
                            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
                            return;
                        }

                        Map<String, Object> map = new HashMap<>();
                        map.put("token", MyApplication.getInstance().getUserBean().getToken());
                        map.put("package_id", info.getPackage_id());
                        map.put("sku_id", info.getPackage_list().get(position).getSku_id());

                        XUtil.Post(Url.BATH_PACKAGEGOODSLIST, map, new MyCallBack<String>() {
                                    @Override
                                    public void onSuccess(String result) {
                                        Log.e("--查看详情==can buy--", result);
                                        super.onSuccess(result);
                                        try {
                                            JSONObject jsonObject = new JSONObject(result);
                                            String res = jsonObject.optString("result");
                                            String info1 = jsonObject.optString("info");
                                            if ("1".equals(res)) {
                                                Gson gson = new Gson();
                                                LookDetailsBean bean = gson.fromJson(result, LookDetailsBean.class);
                                                if (bean.getInfo().getCan_buy().equals("1")) {  //核价下单   可 增 删 替
                                                    Intent intent = new Intent(IndustryDetialsActivity.this, LookDetialsActivity.class);
                                                    intent.putExtra("sku_id", info.getPackage_list().get(position).getSku_id());
                                                    intent.putExtra("package_id", info.getPackage_id());
                                                    intent.putExtra("goods_id", goodsId);
                                                    startActivity(intent);
                                                } else if (bean.getInfo().getCan_buy().equals("0")) {  // 立即购买
                                                    //不能 增 删 替
                                                    Intent intent = new Intent(IndustryDetialsActivity.this, LookDetials2Activity.class);
                                                    intent.putExtra("data", bean);
                                                    intent.putExtra("sku_id", info.getPackage_list().get(position).getSku_id());
                                                    intent.putExtra("type", "1");
                                                    startActivity(intent);
                                                }
                                            } else {
                                                findViewById(R.id.btn_main_right).setVisibility(View.GONE);
                                                if ("-1".equals(res)) {
                                                    info1 = "请重新登录";
                                                }
                                                MyToast(info1);
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFinished() {
                                        super.onFinished();
                                        setData();
                                        closeDialog();
                                    }


                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                        closeDialog();
                                        super.onError(ex, isOnCallback);
                                    }
                                }
                        );

                    }
                });
            }
        });
        comm = info.getComment_list();
        //评论
        evaluation_recycler.setAdapter(new BaseRVAdapter(this, comm) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_evaluation;
            }

            @Override
            public void onBind(final BaseViewHolder holder, int position) {
                holder.setTextView(R.id.realname, comm.get(position).getRealname());
                holder.setTextView(R.id.content, comm.get(position).getContent());
                holder.setTextView(R.id.evalu_time, comm.get(position).getAdd_time());

                ImageLoader.getInstance().displayImage(comm.get(position).getHead_img(), holder.getImageView(R.id.head_img));
                if (position == comm.size() - 1) {
                    holder.getView(R.id.lines).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.lines).setVisibility(View.VISIBLE);
                }

                NoScrollGridView grid = holder.getView(R.id.grid);
                final List<String> imgs = comm.get(position).getImg();
                grid.setAdapter(new BaseAdapter() {
                    @Override
                    public int getCount() {
                        return imgs.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return imgs.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return position;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        Holder holder1;
                        if (convertView == null) {
                            holder1 = new Holder();
                            convertView = View.inflate(IndustryDetialsActivity.this, R.layout.item_img_recycler, null);
                            holder1.img = (ImageView) convertView.findViewById(R.id.img);
                            holder1.img3 = (ImageView) convertView.findViewById(R.id.img3);
                            convertView.setTag(holder1);
                        } else {
                            holder1 = (Holder) convertView.getTag();
                        }

                        ImageLoader.getInstance().displayImage(imgs.get(position), holder1.img3);
                        holder1.img.setBackground(holder1.img3.getDrawable());

                        return convertView;
                    }

                    class Holder {
                        ImageView img, img3;
                    }
                });
            }

        });
        //服务流程
        final List<String> services = info.getService();
        service_recycler.setAdapter(new BaseRVAdapter(this, services) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_service_recycler;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                holder.setTextView(R.id.text, services.get(position));
            }

        });
    }


    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("优惠套餐");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        ImageView search_imgs = (ImageView) findViewById(R.id.search_imgs);
        search_imgs.setImageResource(R.drawable.ci_share);
        findViewById(R.id.ll_search).setOnClickListener(this);
        findViewById(R.id.ll_search).setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.ll_search:
//                MyToast("分享");
                mShareAction.open();
                break;

        }
    }

    private ShareAction mShareAction;
    private UMShareListener mShareListener;

    private void qqShare() {
        mShareListener = new CustomShareListener(this);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(IndustryDetialsActivity.this).setDisplayList(//SHARE_MEDIA.WEIXIN_FAVORITE微信收藏
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
//                .addButton("umeng_sharebutton_copy", "umeng_sharebutton_copy", "umeng_socialize_copy", "umeng_socialize_copy")
//                .addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copy")) {
                            Toast.makeText(IndustryDetialsActivity.this, "复制文本按钮", Toast.LENGTH_LONG).show();
                        } else if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Toast.makeText(IndustryDetialsActivity.this, "复制链接按钮", Toast.LENGTH_LONG).show();

                        } else {
//                            UMWeb web = new UMWeb("http://blog.csdn.net/u011476017/article/details/12620725");
//                            web.setTitle("我的二维码");
//                            web.setDescription("来自优住的分享");
//                            web.setThumb(new UMImage(IndustryDetialsActivity.this, R.drawable.mq_ic_file));
                            //  UMImage image = new UMImage(IndustryDetialsActivity.this, imgu);//网络图片
                            if (info == null) {
                                return;
                            }
                            UMWeb web = new UMWeb(info.getShare_url());
                            web.setTitle(info.getShare_title());
                            web.setDescription(info.getShare_des());
                            web.setThumb(new UMImage(IndustryDetialsActivity.this, info.getShare_img()));


                            new ShareAction(IndustryDetialsActivity.this).withMedia(web)
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();
                        }
                    }
                });
    }

    private static class CustomShareListener implements UMShareListener {

        private WeakReference<BaseActivity> mActivity;

        private CustomShareListener(IndustryDetialsActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST
                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    upfen();
                    Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

                }

            }
        }

        private void upfen() {
            Map<String, Object> map = new HashMap<>();
            map.put("type", 2);
            map.put("packageid", MyApplication.getInstance().jiji);
            Set keys = map.keySet();
            if (keys != null) {
                Iterator iterator = keys.iterator();
                while (iterator.hasNext()) {
                    Object key = iterator.next();
                    Object value = map.get(key);
                    Log.e("----" + key, "" + value + "\n");
                }
            }
            XUtil.Post(Url.API_SHARERETURN, map, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Log.i("----", "onSuccess:= " + result);

                }

                @Override
                public void onFinished() {
                    super.onFinished();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    ex.printStackTrace();
                }
            });


        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST
                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }
}
